const sharp = require('sharp');
const path = require('path');
const fs = require('fs');

const imageController = {
  // 图片压缩
  async compressImage(req, res) {
    try {
      // 检查是否有文件上传
      if (!req.file) {
        return res.status(400).json({ error: '没有上传图片' });
      }

      // 验证文件类型
      if (!req.file.mimetype.startsWith('image/')) {
        fs.unlinkSync(req.file.path); // 删除非图片文件
        return res.status(400).json({ error: '只能上传图片文件' });
      }

      const { quality = 80 } = req.body;
      const inputPath = req.file.path;
      const outputPath = path.join(
        path.dirname(inputPath),
        'compressed-' + path.basename(inputPath)
      );

      try {
        // 获取原始图片信息
        const metadata = await sharp(inputPath).metadata();
        
        // 根据图片格式选择压缩方法
        let compressedImage = sharp(inputPath);
        
        switch(metadata.format.toLowerCase()) {
          case 'jpeg':
          case 'jpg':
            compressedImage = compressedImage.jpeg({ quality: parseInt(quality) });
            break;
          case 'png':
            compressedImage = compressedImage.png({ quality: parseInt(quality) });
            break;
          case 'webp':
            compressedImage = compressedImage.webp({ quality: parseInt(quality) });
            break;
          default:
            // 默认转换为JPEG
            compressedImage = compressedImage.jpeg({ quality: parseInt(quality) });
        }

        // 压缩图片
        await compressedImage.toFile(outputPath);

        // 获取压缩后的文件大小
        const stats = fs.statSync(outputPath);
        
        // 清理原始文件
        fs.unlinkSync(inputPath);

        // 检查压缩后的文件是否存在且大小正常
        if (!fs.existsSync(outputPath) || stats.size === 0) {
          throw new Error('压缩后的文件无效');
        }

        res.json({
          success: true,
          message: '图片压缩成功',
          filename: path.basename(outputPath),
          size: stats.size,
          originalSize: req.file.size,
          format: metadata.format
        });
      } catch (error) {
        // 清理文件
        if (fs.existsSync(inputPath)) {
          fs.unlinkSync(inputPath);
        }
        if (fs.existsSync(outputPath)) {
          fs.unlinkSync(outputPath);
        }
        throw error;
      }
    } catch (error) {
      console.error('图片压缩错误:', error);
      res.status(500).json({ 
        error: error.message || '图片压缩失败',
        details: process.env.NODE_ENV === 'development' ? error.stack : undefined
      });
    }
  },

  // 图片剪裁
  async cropImage(req, res) {
    try {
      if (!req.file) {
        return res.status(400).json({ error: '没有上传图片' });
      }

      const { width, height, left, top } = req.body;
      const inputPath = req.file.path;
      const outputPath = path.join(
        path.dirname(inputPath),
        'cropped-' + path.basename(inputPath)
      );

      await sharp(inputPath)
        .extract({
          width: parseInt(width),
          height: parseInt(height),
          left: parseInt(left),
          top: parseInt(top)
        })
        .toFile(outputPath);

      res.json({
        message: '图片剪裁成功',
        filename: path.basename(outputPath)
      });
    } catch (error) {
      console.error('图片剪裁错误:', error);
      res.status(500).json({ error: '图片剪裁失败' });
    }
  },

  // 图片格式转换
  async convertImage(req, res) {
    try {
      if (!req.file) {
        return res.status(400).json({ error: '没有上传图片' });
      }

      const { format } = req.body;
      const inputPath = req.file.path;
      const outputPath = path.join(
        path.dirname(inputPath),
        'converted-' + path.basename(inputPath, path.extname(inputPath)) + '.' + format
      );

      const image = sharp(inputPath);
      switch (format.toLowerCase()) {
        case 'jpeg':
        case 'jpg':
          await image.jpeg().toFile(outputPath);
          break;
        case 'png':
          await image.png().toFile(outputPath);
          break;
        case 'webp':
          await image.webp().toFile(outputPath);
          break;
        default:
          return res.status(400).json({ error: '不支持的格式' });
      }

      res.json({
        message: '格式转换成功',
        filename: path.basename(outputPath)
      });
    } catch (error) {
      console.error('格式转换错误:', error);
      res.status(500).json({ error: '格式转换失败' });
    }
  },

  // 添加水印
  async addWatermark(req, res) {
    try {
      if (!req.file) {
        return res.status(400).json({ error: '没有上传图片' });
      }

      const { text, fontSize = 48, opacity = 0.5 } = req.body;
      const inputPath = req.file.path;
      const outputPath = path.join(
        path.dirname(inputPath),
        'watermarked-' + path.basename(inputPath)
      );

      // 创建水印图片
      const svgBuffer = Buffer.from(`
        <svg width="500" height="100">
          <text x="50%" y="50%" font-family="Arial" font-size="${fontSize}" 
                fill="rgba(255,255,255,${opacity})" text-anchor="middle" dominant-baseline="middle">
            ${text}
          </text>
        </svg>
      `);

      const image = sharp(inputPath);
      const metadata = await image.metadata();

      await image
        .composite([
          {
            input: svgBuffer,
            gravity: 'center'
          }
        ])
        .toFile(outputPath);

      res.json({
        message: '水印添加成功',
        filename: path.basename(outputPath)
      });
    } catch (error) {
      console.error('水印添加错误:', error);
      res.status(500).json({ error: '水印添加失败' });
    }
  },

  // 下载处理后的图片
  downloadImage(req, res) {
    const { filename } = req.params;
    const filePath = path.join(__dirname, '../../uploads', filename);

    if (!fs.existsSync(filePath)) {
      return res.status(404).json({ error: '文件不存在' });
    }

    res.download(filePath);
  }
};

module.exports = imageController; 